//
//  personViewController.m
//  lmq
//
//  Created by 千翼网络科技 on 2017/1/23.
//  Copyright © 2017年 yuanxin. All rights reserved.
//

#import "personViewController.h"
#import "personTableViewCell.h"
#import "Masonry.h"
#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "ICN_HeadImageSelView.h"
#import "UIImageView+WebCache.h"
#import "userViewController.h"

#import "AFHTTPSessionManager.h"
#import "AFURLSessionManager.h"
#import "AFURLRequestSerialization.h"
#import "AFURLResponseSerialization.h"
#import "UIButton+AddAction.h"

#import "AFHTTPRequestOperationManager.h"
#import "XiuGaiPhoneViewController.h"

@interface personViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate, STPhotoKitDelegate>
{
    UIView *grayView;
    NSString *strUrl;
}
@property (nonatomic, strong) UIButton *touButton;
@property (strong, nonatomic) ICN_HeadImageSelView *changeHeadImageView;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImageView *shoppicImage;


@end

@implementation personViewController
#pragma mark - ---------- 懒加载 ----------
- (ICN_HeadImageSelView *)changeHeadImageView {
    if (!_changeHeadImageView)
    {
        _changeHeadImageView = [[NSBundle mainBundle] loadNibNamed:@"ICN_HeadImageSelView" owner:self options:nil].lastObject;
    }
    return _changeHeadImageView;
}
- (void)viewWillAppear:(BOOL)animated{

    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setTitle:@"个人信息"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction)];
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
    [productParams setValue:tokenStr forKey:@"token"];
  
    [[MNetworkHandler sharedInstance]conURL:Member_Info
                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       
                                       NSDictionary *dict1=[returnData objectForKey:@"data"];
                                       //   strHeader_img= [dict1 objectForKey:@"header_img"];
                                       NSString *strPhone= [dict1 objectForKey:@"phone"];
                                       NSString *strName= [dict1 objectForKey:@"name"];
//                                       NSString *strPic = @"http://lmq.quyum.cn/";
//                                       
//                                       NSString *str = [strPic stringByAppendingString:[dict1 objectForKey:@"header_img"]];
                                       
                                       NSString *urlWare=[dict1 objectForKey:@"header_img"];
                                       NSString *str=manage(AP_HOST, urlWare);
                                       strUrl = [str stringByReplacingOccurrencesOfString:@"\\" withString:@"/"];
                                       
                                       
                                       
                                       perArr =[[NSMutableArray alloc]init];
                                       [perArr addObject:strName];
                                       [perArr addObject:strPhone];
                                       [personTableView reloadData];
                                   }
                                   else {
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                   }
                               } failureBlock:^(NSError *error) {
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];

    
    personArr=[[NSMutableArray alloc]init];
    
    NSMutableDictionary *dict1=[[NSMutableDictionary alloc]init];
    [dict1 setObject:@"用户名" forKey:@"namen"];
    
    
    NSMutableDictionary *dict2=[[NSMutableDictionary alloc]init];
    [dict2 setObject:@"手机号" forKey:@"namen"];
    
    
    [personArr addObject:dict1];
    [personArr addObject:dict2];
    
    
    personTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    personTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    personTableView.delegate=self;
    personTableView.dataSource=self;
    personTableView.backgroundColor=[ZJCModel colorWithString:@"f2f2f2"];
    [self.view addSubview:personTableView];

    // Do any additional setup after loading the view.
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -----UITableViewDataSource-----

//返回分区数(默认为1)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//返回每一行的cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return perArr.count;
}

//自定义section的头部
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *xView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, (75))];
    xView.backgroundColor=[UIColor whiteColor];
    UILabel *touLabel=[[UILabel alloc]initWithFrame:CGRectMake((10), (30), (40), (15))];
    touLabel.text=@"头像";
    [xView addSubview:touLabel];
    self.touButton=[[UIButton alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH-(80), (12.5), (50), (50))];

    self.shoppicImage = [[UIImageView alloc] init];
    
    
    self.shoppicImage.frame = CGRectMake(DEF_SCREEN_WIDTH-(80), (12.5), (50), (50));
    [self.shoppicImage sd_setImageWithURL:[NSURL URLWithString:strUrl]];

    
    [self.touButton setBackgroundImage:self.shoppicImage.image forState:UIControlStateNormal];
    self.touButton.layer.masksToBounds=YES;
    self.touButton.layer.cornerRadius=(25);
//    self.touButton.layer.borderColor=[ZJCModel colorWithString:@"cccccc"].CGColor;
    [self.touButton addTarget:self action:@selector(headPortrait) forControlEvents:UIControlEventTouchUpInside];
    
    [xView addSubview:self.touButton];
    return xView;
}
//自定义section头部的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return (75);
}

#pragma mark -----UITableViewDelegate-----
//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (45);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    personTableViewCell *cell=(personTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"personTableViewCell"];
    if (cell == nil) {
        cell=[[personTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"personTableViewCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.titLable1.text=perArr[indexPath.row];
    cell.titLable.text=[personArr[indexPath.row] objectForKey:@"namen"];
    return cell;
}
#pragma mark - ---------- 每个Cell的点击事件 ----------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (indexPath.row == 1) {
        XiuGaiPhoneViewController *detailsVC=[[XiuGaiPhoneViewController alloc]init];

        [self.navigationController pushViewController:detailsVC animated:YES];
    }
   
}

//去掉UItableview headerview黏性(sticky)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == personTableView)
    {
        CGFloat sectionHeaderHeight = 75; //sectionHeaderHeight
        if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
        } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
        }
    }
}
- (void)headPortrait{

    [self editImageSelected];



}
#pragma mark - --- delegate 视图委托 ---

#pragma mark - 1.STPhotoKitDelegate的委托

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    // [self.imageButton setImage:resultImage forState:UIControlStateNormal];
    [self.touButton setBackgroundImage:resultImage forState:UIControlStateNormal];
    
    self.image = resultImage;
}

#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        
        [photoVC setSizeClip:CGSizeMake(self.touButton.frame.size.width*4, self.touButton.frame.size.width*4)];
        
        
        [self presentViewController:photoVC animated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark - --- event response 事件相应 ---
- (void)editImageSelected
{
    grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
    grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
    
    [[UIApplication sharedApplication].keyWindow addSubview:grayView];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
    [grayView addGestureRecognizer:tapGesture];
    
    [grayView addSubview:self.changeHeadImageView];
    [self.changeHeadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(DEF_SCREEN_WIDTH, 160));
    }];
    
    self.changeHeadImageView.layer.cornerRadius = 8;
    [self.changeHeadImageView.takePhotoButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
        [grayView removeFromSuperview];
        if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
            [controller setDelegate:self];
            [self presentViewController:controller animated:YES completion:nil];
        }else {
            NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
        }
    }];
    [self.changeHeadImageView.localAlbumButton addAction:^(NSInteger tag) {
        UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        [controller setDelegate:self];
        [grayView removeFromSuperview];
        if ([controller isAvailablePhotoLibrary]) {
            [self presentViewController:controller animated:YES completion:nil];
        }
    }];
    [self.changeHeadImageView.closeViewButton addAction:^(NSInteger tag) {
        [self dismissContactView];
    }];
}

- (void)dismissContactView {
    [grayView removeFromSuperview];
}
- (void)saveAction{

    
    NSData *data = UIImageJPEGRepresentation(self.image, 0.001);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    

   
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    NSString *tokenStr=[PublicFunction getConfigWithKey:@"token"];
    [productParams setValue:tokenStr forKey:@"token"];
//    NSString *member = [PublicFunction getConfigWithKey:@"uid"];
//    [productParams setValue:member forKey:@"member_id"];
    [productParams setValue:encodedImageStr forKey:@"pic"];
    
    
    [[MNetworkHandler sharedInstance]conURL:Member_uploadHeadByBase                                networkType:NetWorkPOST
                                     params:productParams
                                   delegate:nil
                                    showHUD:NO
                               successBlock:^(id returnData) {
                                   if ([[returnData objectForKey:@"code"]intValue]==1) {
                                       NSLog(@"success");

                                        [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                       [self.navigationController popViewControllerAnimated:YES];
                                       


                                   }
                                   else {
                                       [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
                                   }
                               } failureBlock:^(NSError *error) {
                                   NSLog(@"%@",error);
                                   [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
                               }];

    
    
    
    
  
    
    
}


//压缩图片
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

@end
